package com.zhiche.lisa.oms.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.enums.TableStatusEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.core.utils.Account.JwtTokenUtil;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.SnowFlakeId;
import com.zhiche.lisa.oms.dao.mapper.OrderMapper;
import com.zhiche.lisa.oms.dao.model.*;
import com.zhiche.lisa.oms.dao.model.bo.GenerateOrderBO;
import com.zhiche.lisa.oms.dao.model.bo.ShipLineInfoBO;
import com.zhiche.lisa.oms.dao.model.bo.ShippingInfoBO;
import com.zhiche.lisa.oms.dto.*;
import com.zhiche.lisa.oms.enums.FourPeopleEnum;
import com.zhiche.lisa.oms.service.*;
import com.zhiche.lisa.oms.service.util.ErpUtil;
import com.zhiche.lisa.oms.service.util.MdmUtil;
import com.zhiche.lisa.oms.util.TokenUtil;
import com.zhiche.lisa.oms.vo.CarrierInfoLineVO;
import com.zhiche.lisa.oms.vo.LocationVo;
import com.zhiche.lisa.oms.vo.OrderVO;
import com.zhiche.lisa.oms.vo.ShipmentInfoVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

//import com.zhiche.lisa.repos.mapper.oms.Ord

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-06-18
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private IOrderItemService orderItemService;

    @Autowired
    private IOrderContactService orderContactService;

    @Autowired
    private IOrderLocationService orderLocationService;

    @Autowired
    private IOrderAssignService orderAssignService;

    @Autowired
    private ILocationService locationService;

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private MdmUtil mdmUtil;

    @Autowired
    private ErpUtil erpUtil;


    @Value("${erp.getNewestShipByLicenseUrl}")
    private String getNewestShipByLicenseUrl;

    //连接超时时间
    @Value("${erp.socketTimeout}")
    private int socketTimeout;

    @Value("${lisa.tms.generateShipOrderURL}")
    private String generateShipOrder;

    @Value("${lisa.tms.getShipOrderByItemIdURL}")
    private String getShipOrderByItemIdURL;

    @Value("${lisa.lspm.authedCarrierPlateURL}")
    private String authedCarrierPlateURL;

    @Value("${uaa.getTentUrl}")
    private String getTentUrl;

    @Value("${security.oauth2.client.access-token-uri}")
    private String getTokenUrl;

    @Value("${security.oauth2.client.clientId}")
    private String getClinetId;

    @Value("${security.oauth2.client.clientSecret}")
    private String getClientSecret;

    @Value("${lisa.oms.generateOrderUrl}")
    private String generateOrderUrl;

    @Value("${lisa.tms.addShipmentURL}")
    private String addShipmentURL;

    @Value("${lisa.lspm.getCarrierInfoByPlate}")
    private String getCarrierInfoByPlate;

    @Autowired
    private SnowFlakeId snowFlakeId;

    @Value("${integration.getPriceAndMilesUrl}")
    private String getPriceAndMilesUrl;

    @Value("${integration.url}")
    private String integrationUrl;

    @Value("${lisa.bms.insertPriceIncomingUrl}")
    private String insertPriceIncomingUrl;

    @Value("${lisa.bms.updateIncomingPriceByTaskCodeUrl}")
    private String updateIncomingPriceByTaskCodeUrl;

    @Value("${lisa.bms.deletePriceIncomingUrl}")
    private String deletePriceIncomingUrl;

    @Value("${integration.queryListOriginationUrl}")
    private String queryListOriginationUrl;

    @Value("${lisa.lspm.getDriverInfoById}")
    private String getDriverInfoById;

    @Value("${lisa.lspm.isUnlcnFleetDriverUrl}")
    private String isUnlcnFleetDriverUrl;

    @Override
    public void getAuthedCarrierPlate() {
        List<TechAccount> techAccountList = getToken();
        if (CollectionUtils.isNotEmpty(techAccountList)) {
            for (TechAccount techAccount : techAccountList) {
                if (Objects.nonNull(techAccount.getTechAccountIdentifier())) {
                    String token = getTenantToken(techAccount.getTechAccountIdentifier());
                    LOGGER.info("getAuthedCarrierPlate  techAccount token:{} ", token);
                    if (!StringUtils.isEmpty(token)) {
                        List<String> plateList = getCarrierPlates(token, techAccount.getId());
                        if (CollectionUtils.isNotEmpty(plateList)) {
//                    String licenses = StringUtils.join(plateList.toArray(), ",");
                            createOrderByErpShipment(token, plateList, techAccount.getId());
//                    generateOrder(token, plateList);
                        }
                    }
                }
            }
        }

    }

    //    @Transactional
    @Override
    public void createOrderByErpShipment(String authorization, List<String> plateList, Long teanantId) throws
            BaseException {
        for (String license : plateList) {
            // 则调用接口，抓取调度指令
            LOGGER.info("createOrderByErpShipment  抓取指令 plateno:{},teanantId:{}", license, teanantId);
            ShippingInfoBO shippingInfoBO = getNewestShipByERP(license);
            if (!Objects.isNull(shippingInfoBO)) {
                Wrapper<Order> orderWrapper = new EntityWrapper<>();
                orderWrapper.eq("customer_order_id", shippingInfoBO.getVcshipno());
                List<Order> orderList = baseMapper.selectListNoTenant(orderWrapper);
                // 如果订单不存在就插入，存在则更新
                if (CollectionUtils.isEmpty(orderList)) {
                    // 插入
                    createOrder(authorization, shippingInfoBO, teanantId);
                }
            }
        }
    }


    //    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void createOrder(String authorization, ShippingInfoBO shippingInfoBO, Long teanantId) {

        ShipmentAutoDTO shipmentAutoDTO = new ShipmentAutoDTO();

        // 发运指令下所有明细
        List<ShipLineInfoBO> shipLineInfoBOList = shippingInfoBO.getShipLineInfoBOList();
        // 根据明细生成的订单数
        List<GenerateOrderBO> generateOrderBOList = new ArrayList<>();

        // 组装头和明细关系
        for (ShipLineInfoBO shipLineInfoBO : shipLineInfoBOList) {
            GenerateOrderBO generateOrderBO = getGenerateOrderBO(shipLineInfoBO, generateOrderBOList);
            generateOrderBO.addShipLineInfoBO(shipLineInfoBO);
        }

        for (GenerateOrderBO generateOrderBO : generateOrderBOList) {
            LOGGER.info("erp 指令生成订单BO :{}", JSON.toJSONString(generateOrderBO));
            //创建订单
            Order order = new Order();
            // 订单编号
            String code = "CO" + snowFlakeId.nextId();
            order.setCode(code);
            // 订单备注
            order.setComment(shippingInfoBO.getVcmemo());
            // 业务类型
            order.setTos("fleet");
            // 客户下单时间
            order.setGmtIssue(shippingInfoBO.getDtdate());
            // 系统创建时间
            order.setGmtCreate(new Date());
            // 客户标识
            order.setCustomerId("unlcn");
            // 客户订单编号
            order.setCustomerOrderId(shippingInfoBO.getVcshipno());

            order.setTenantId(teanantId);

            // 插入订单
            insert(order);

            //创建联系人
            OrderContact orderContact = new OrderContact();
            // 联系人姓名
            orderContact.setContactsName(shippingInfoBO.getVcdrivername());
            // 联系人电话
            orderContact.setContactsPhone(shippingInfoBO.getVcmobile());
            // 订单编码
            orderContact.setOrderCode(order.getCode());
            orderContact.setTenantId(teanantId);
            // 保存订单各类联系人信息
            orderContactService.insert(orderContact);

            order.setOrderContact(orderContact);

            // 判断订单明细里的提货地点信息是否存在，不存在则插入
            LocationVo startLocation = locationService.getLocationByValue("发货点", generateOrderBO.getVcstartcityname(), teanantId);
            if (startLocation == null) {
                // 插入

                startLocation = locationService.insertOrUpdateLocation("发货点",
                        generateOrderBO.getVcstartcityname(), generateOrderBO.getVcstartcityname(), null, teanantId);
                if (startLocation == null) {
                    throw new BaseException("获取提货点信息失败");
                }
            }

            // 判断订单明细里的交货地点信息是否存在，不存在则插入
            LocationVo endLocation = locationService.getLocationByValue("交货点", generateOrderBO.getVcendcityname(), teanantId);
            if (endLocation == null) {
                // 插入
                endLocation = locationService.insertOrUpdateLocation("交货点",
                        generateOrderBO.getVcendcityname(), generateOrderBO.getVcendcityname(), null, teanantId);
                if (endLocation == null) {
                    throw new BaseException("获取交货点信息失败");
                }
            }

            OrderLocation orderLocation = new OrderLocation();
            // 订单 id
            orderLocation.setOrderId(order.getId());
            // 发货点编码
            orderLocation.setShippingLocationId(startLocation.getId());
            // 交货点编码
            orderLocation.setDeliveryLocationId(endLocation.getId());
            // 创建时间
            orderLocation.setGmtCreate(new Date());
            orderLocation.setTenantId(teanantId);
            // 订单各类地址信息
            orderLocationService.insert(orderLocation);

            order.setOrderLocation(orderLocation);

            List<OrderItem> orderItems = Lists.newArrayList();
            for (ShipLineInfoBO shipLineInfoBO : generateOrderBO.getShipLineInfoBOList()) {
                //插入订单ITEM
                OrderItem orderItem = new OrderItem();
                // 订单 id
                orderItem.setOrderId(order.getId());
                // 数量
                orderItem.setAmount(1);
                // 度量单位
                orderItem.setUom("辆");
                // 所下订单中的原始货物标识信息(客户系统推送或录单人录入)
                //TODO VCVIN

                if (!StringUtils.isEmpty(shipLineInfoBO.getVcvin()) && !"null".equals(shipLineInfoBO.getVcvin())) {
                    orderItem.setIssueItemId(shipLineInfoBO.getVcvin());
                }
                if (!StringUtils.isEmpty(shipLineInfoBO.getVcstyleno()) && !"null".equals(shipLineInfoBO.getVcstyleno())) {
                    orderItem.setMaterial(shipLineInfoBO.getVcstyleno());
                }

                orderItem.setTenantId(teanantId);
                // 创建时间
//                orderItem.setGmtCreate(new Date());
                orderItems.add(orderItem);

                // 保存订单订单明细

            }
            orderItemService.insertBatch(orderItems);
            order.setOrderItemList(orderItems);

            shipmentAutoDTO.addOrder(order);
        }

        shipmentAutoDTO.setTransportationId(shippingInfoBO.getVclicense());
        shipmentAutoDTO.setTenantId(teanantId);

        Date assignDate = new Date();

        if (!CollectionUtils.isEmpty(generateOrderBOList)) {
            //下订单，自动生成TMS的运单、任务和装车单
            List<OrderAssign> orderAssignList = autoShipment(authorization, shipmentAutoDTO, generateShipOrder);
            // 回写下发单委托单号（下游系统回写单号）
            if (CollectionUtils.isNotEmpty(orderAssignList)) {
                for (OrderAssign orderAssign : orderAssignList) {
                    orderAssign.setGmtAssign(assignDate);
                    orderAssign.setAssignLog("成功");
                    orderAssign.setTenantId(teanantId);
                    orderAssignService.insert(orderAssign);
                }
            }
        }
        //fix  调整运力平台司机报班状态为已安排
        CarrierInfoLineVO infoLineVO = selectCarrierInfoByPlate(shippingInfoBO.getVclicense());
        LOGGER.info("erp指令--->根据车牌查询司机信息result:{}", JSONObject.toJSONString(infoLineVO));
        if (infoLineVO != null) {
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            // 连接lspm 将司机报班状态调整为已安排--
            headNamePairs.add(new BasicNameValuePair("checkInType", "IU"));
            LOGGER.info("指令新增 连接LSPM 调整司机报班状态:url{},driverId:{},checkinId:{}", getDriverInfoById, infoLineVO.getDriverId(),shippingInfoBO.getCheckinId());
            String result = HttpClientUtil.get(getDriverInfoById + "/" + infoLineVO.getDriverId()+"/"+shippingInfoBO.getCheckinId(), headNamePairs, null, socketTimeout);
            LOGGER.info("指令新增 连接LSPM 调整司机报班状态:url{},result:{}", getDriverInfoById, result);
        }
    }

    ///**
    // * 发运时查询OMS 订单获取指令信息
    // */
    //@Override
    //public Order queryOrder(Map<String, String> condition) {
    //    if (condition != null && !condition.isEmpty()) {
    //        EntityWrapper<OrderAssign> ew = new EntityWrapper<>();
    //        String toc = condition.get("tmsOrderCode");
    //        if (StringUtils.isBlank(toc)) {
    //            throw new BaseException("msOrderCode 不能为空");
    //        }
    //        ew.eq("consign_code", toc)
    //                .eq("is_delete", TableStatusEnum.STATUS_0.getCode())
    //                .orderBy("id", false);
    //        OrderAssign assign = orderAssignService.selectOne(ew);
    //        if (assign == null) {
    //            throw new BaseException("未查询到tmsOrderCode:" + toc + "的下发订单信息");
    //        }
    //        EntityWrapper<Order> oew = new EntityWrapper<>();
    //        oew.eq("code", assign.getOrderCode())
    //                .eq("is_delete", TableStatusEnum.STATUS_0.getCode())
    //                .orderBy("id", false);
    //        Order order = selectOne(oew);
    //        if (order == null) {
    //            throw new BaseException("未查询到omsOrderCode:" + assign.getOrderCode() + "的订单信息");
    //        }
    //        return order;
    //    }
    //    return null;
    //}

    /**
     * 根据id查询订单信息
     *
     * @param id
     */
    @Override
    public Order queryOrderById(Long id) {
        Order cn = null;
        Wrapper<Order> ew = new EntityWrapper<>();
        if (id != null) {
            ew.eq("id", id);
            cn = this.selectOne(ew);
        }
        return cn;
    }


    /**
     * 调用接口获取调度指令
     */
    private ShippingInfoBO getNewestShipByERP(String license) {
        ShippingInfoBO shippingInfoBO = null;

        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", ""));
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("vclicense", license));
        String strReturn = HttpClientUtil.get(getNewestShipByLicenseUrl, headNamePairs, params, socketTimeout);
        if (!StringUtils.isEmpty(strReturn)) {
            RestfulResponse<ShippingInfoBO> restVO = JSON.parseObject(strReturn, new
                    TypeReference<RestfulResponse<ShippingInfoBO>>() {
                    });
            shippingInfoBO = restVO.getData();
        }
        return shippingInfoBO;
    }

//    private ShipOrder getShipOrderInfo(String authorization,Long itemId) {
//        ShipOrder shipOrder = null;
//        List<NameValuePair> headNamePairs = Lists.newArrayList();
//        headNamePairs.add(new BasicNameValuePair("Authorization",authorization));
//        List<NameValuePair> params = Lists.newArrayList();
//        params.add(new BasicNameValuePair("itemId", String.valueOf(itemId)));
//        String strReturn = HttpClientUtil.get(getShipOrderByItemIdURL,headNamePairs,params,socketTimeout);
//        if(!StringUtils.isEmpty(strReturn)){
//            RestfulResponse<ShipOrder> restVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<ShipOrder>>(){});
//            shipOrder = restVO.getData();
//        }
//        return shipOrder;
//    }

//    public void generateShipOrder(String authorization,GenerateShipOrderBO generateShipOrderBO) {
//        List<NameValuePair> headNamePairs = Lists.newArrayList();
//        headNamePairs.add(new BasicNameValuePair("Authorization",authorization));
//        String strReturn = HttpClientUtil.postJson(generateShipOrder, headNamePairs, JSON.toJSONString(generateShipOrderBO), socketTimeout);
//        Integer code = null;
//        String message = null;
//        if(!StringUtils.isEmpty(strReturn)){
//            RestfulResponse<ShipOrder> restVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<ShipOrder>>(){});
//            code = restVO.getCode();
//            message = restVO.getMessage();
//        }
//
//        if (StringUtils.isEmpty(strReturn) || code!=0) {
//            throw new BaseException("生成运单异常：" + message);
//        }
//    }

    private List<OrderAssign> autoShipment(String authorization, Object params, String url) {
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        String strReturn = HttpClientUtil.postJson(url, headNamePairs,
                JSON.toJSONString(params), socketTimeout + 50000);//10秒改为1分钟
        if (!StringUtils.isEmpty(strReturn)) {
            RestfulResponse<List<OrderAssign>> restVO = JSON.parseObject(strReturn,
                    new TypeReference<RestfulResponse<List<OrderAssign>>>() {
                    });
            if (restVO.getCode() == 0) {
                return restVO.getData();
            } else {
                LOGGER.error("生成运单异常 url:{},message:{}", url, restVO.getMessage());
                throw new BaseException("生成运单异常：" + restVO.getMessage());
            }

        } else {
            LOGGER.error("连接TMS异常" + url);
//            throw new BaseException("连接TMS异常");
        }
        return null;
    }


    /**
     * 得到租户应用管理员
     *
     * @return
     */
    private List<TechAccount> getToken() {
//        List<String> techAccountIdentifiers = Lists.newArrayList();
        String strReturn = HttpClientUtil.get(getTentUrl, null, 10000);
        RestfulResponse<List<TechAccount>> result = JSON.parseObject(strReturn,
                new TypeReference<RestfulResponse<List<TechAccount>>>() {
                });
        if (result.getCode() == 0) {
            return result.getData();
        } else {
            return null;
        }
//        JSONObject jsonObject = JSON.parseObject(strReturn);
//        int status = jsonObject.getInteger("code");
//        if(status == 0){
//            JSONArray jsonArray = jsonObject.getJSONArray("data");
//            if(CollectionUtils.isNotEmpty(jsonArray)){
//                jsonArray.forEach(object1 -> {
//                    JSONObject jsonObject1 = (JSONObject) object1;
//                    String techAccountIdentifier = jsonObject1.getString("techAccountIdentifier");
//                    techAccountIdentifiers.add(techAccountIdentifier);
//                });
//            }
//        }
//        return techAccountIdentifiers;
    }

    /**
     * * 生成订单
     *
     * @param authorization
     * @param plateList
     * @return
     */
    private Boolean generateOrder(String authorization, List<String> plateList, Long teanantId) {
        Boolean returnValue = false;
//        String licenses = StringUtils.join(plateList.toArray(), ",");
//        List<NameValuePair> headNamePairs = Lists.newArrayList();
//        headNamePairs.add(new BasicNameValuePair("Authorization",authorization));
//        Map<String, String> paramsMap = Maps.newHashMap();
//        paramsMap.put("licenses",licenses);

        createOrderByErpShipment(authorization, plateList, teanantId);


//        String strReturn = HttpClientUtil.post(generateOrderUrl,headNamePairs,paramsMap,socketTimeout);
//        if(!StringUtils.isEmpty(strReturn)){
//            RestfulResponse<Boolean> result = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<Boolean>>(){});
//            returnValue = result.getData();
//        }
        return true;
    }

    private String getTenantToken(String techAccountIdentifier) {
        Map<String, String> parmers = Maps.newHashMap();
        parmers.put("username", techAccountIdentifier);
        parmers.put("password", "123456");
        parmers.put("client_id", getClinetId);
        parmers.put("client_secret", getClientSecret);
        parmers.put("grant_type", "password");
        String result = HttpClientUtil.post(getTokenUrl, parmers, socketTimeout);
        if (StringUtils.isEmpty(result)) return null;
        JSONObject jsonObject2 = JSON.parseObject(result);
        if (Objects.nonNull(jsonObject2)) {
            String access_token = jsonObject2.getString("access_token");
            String authorization = "Bearer " + access_token;
            return authorization;
        } else {
            return null;
        }
    }

    private List<String> getCarrierPlates(String token, Long tenantId) {
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", token));
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("tenantId", tenantId.toString()));
        String strReturn = HttpClientUtil.get(authedCarrierPlateURL, headNamePairs, params, socketTimeout);
        if (!StringUtils.isEmpty(strReturn)) {
            RestfulResponse<List<String>> restVO = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<List<String>>>() {
            });
            List<String> plateList = restVO.getData();
            if (!CollectionUtils.isEmpty(plateList)) {
                LOGGER.info(plateList.size() + "条已经认证的牵引车车牌 ===plateList:{}", JSON.toJSONString(plateList));
            } else {
                LOGGER.info("不存在已经认证的牵引车车牌 ====================");
            }
            return plateList;
        } else {
            return null;
        }

    }

    private GenerateOrderBO getGenerateOrderBO(ShipLineInfoBO shipLineInfoBO, List<GenerateOrderBO> generateOrderBOList) {
        for (GenerateOrderBO generateOrderBO : generateOrderBOList) {
            if (shipLineInfoBO.getIstartcityid().equals(generateOrderBO.getIstartcityid())
                    && shipLineInfoBO.getIendcityid().equals(generateOrderBO.getIendcityid())) {
                return generateOrderBO;
            }
        }
        GenerateOrderBO generateOrderBO = new GenerateOrderBO();
        BeanUtils.copyProperties(shipLineInfoBO, generateOrderBO);
        generateOrderBOList.add(generateOrderBO);
        return generateOrderBO;
    }

    @Override
    public Boolean loginWithOutToken(ShipmentInfoVO shipmentInfoVO) {
        CarrierInfoLineVO carrierInfoLineVO = selectCarrierInfoByPlate(shipmentInfoVO.getPlateNo());
        String authorization = tokenUtil.getTenantToken("tech-" + carrierInfoLineVO.getTenantId());
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        HttpClientUtil.postJson("http://localhost:8090/order/createOrder", headNamePairs, JSONObject.toJSONString(shipmentInfoVO), 100000);
        return true;
    }

    /**
     * 同步数据添加订单信息
     */
    @Override
    @Transactional
    public void addOrder(ShipmentInfoVO shipmentInfoVO, String authorization) {
        CarrierInfoLineVO carrierInfoLineVO = selectCarrierInfoByPlate(shipmentInfoVO.getPlateNo());
        //authorization = tokenUtil.getTenantToken("tech-" + carrierInfoLineVO.getTenantId());
        String token = StringUtils.substringAfter(authorization, "Bearer ");
        JwtAccountVO accountVO = JwtTokenUtil.decodeJwt(token);
        shipmentInfoVO.setTenantId(Long.valueOf(accountVO.getTenantId()));
        shipmentInfoVO.setCreator(accountVO.getAccountId());
        if (Objects.nonNull(carrierInfoLineVO.getLspId()) && StringUtils.isNotEmpty(carrierInfoLineVO.getLspName())) {
            if (StringUtils.isEmpty(shipmentInfoVO.getTransactionCode())) throw new BaseException("数据处理方式为空");
            // 根据明细生成的订单数
            List<ShipmentInfoVO> shipmentInfoVOS = new ArrayList<>();
            // 组装头和明细关系
            if (CollectionUtils.isNotEmpty(shipmentInfoVO.getShipTaskDTOList())) {
                for (OrderVO orderVO : shipmentInfoVO.getShipTaskDTOList()) {
                    ShipmentInfoVO shipmentInfoVO1 = getGenerateOrder(orderVO, shipmentInfoVOS);
                    shipmentInfoVO1.addOrderVO(orderVO);
                }
            } else {
                // 明细为空,走删除逻辑
                deleteOrder(shipmentInfoVO, authorization);
            }
            switch (shipmentInfoVO.getTransactionCode()) {
                case "IU":
                    insertOrder(shipmentInfoVOS, shipmentInfoVO, authorization);
                    break;
                case "R":
                    updateOrder(shipmentInfoVO, authorization);
                    break;
                default:
                    deleteOrder(shipmentInfoVO, authorization);
                    break;
            }

            new Thread(() -> {
                List<NameValuePair> headNamePairs = Lists.newArrayList();
                headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
                String result = HttpClientUtil.get(isUnlcnFleetDriverUrl + "/" + shipmentInfoVO.getDriverId(), headNamePairs, null, socketTimeout);
                LOGGER.info("result (判断司机是否是中联自有车队返回结果) url:{},erpResult:{}", isUnlcnFleetDriverUrl + "/" + shipmentInfoVO.getDriverId(), result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                Boolean data = jsonObject.getBoolean("data");
                if (data) {
                    try {
                        shipmentInfoVO.setGmtModified(new Date());
                        String erpResult = HttpClientUtil.postJson("", headNamePairs, JSONObject.toJSONString(shipmentInfoVO), socketTimeout);
                        LOGGER.info("erpResult (推送erp数据返回结果) url:{},params:{},erpResult:{}", "", JSONObject.toJSONString(shipmentInfoVO), erpResult);
                    } catch (Exception e) {
                        LOGGER.error("调度指令连接erp失败 error{}", e);
                    }
                }
            }).start();

        }
    }


    /**
     * 添加订单
     */
    private Boolean insertOrder(List<ShipmentInfoVO> shipmentInfoVOList,
                                ShipmentInfoVO shipmentInfoVO,
                                String authorization) {
        //当前登录用户租户id
        Long teanantId = shipmentInfoVO.getTenantId();
        ShipmentOrderDTO shipmentOrderDTO = new ShipmentOrderDTO();
        BeanUtils.copyProperties(shipmentInfoVO, shipmentOrderDTO);
        //获取运输方式id
        Long transTypeId = getTransTypeId(shipmentInfoVO.getTransportModeId());
        if (null == transTypeId) {
            LOGGER.error("未查询到对应的运输方式 error:{}", shipmentInfoVO.getTransportModeId());
        }
        for (ShipmentInfoVO shipmentInfo : shipmentInfoVOList) {//生成订单
            Order order = new Order();
            order.setCode("CO" + snowFlakeId.nextId());
            order.setComment(shipmentInfo.getRemarks());
            order.setTos("fleet");
            order.setGmtIssue(new Date());
            order.setGmtCreate(new Date());
            order.setCustomerOrderId(shipmentInfo.getShipmentId());
            order.setTransTypeId(transTypeId);
            order.setTenantId(teanantId);
            order.setCurrentStatus(shipmentInfo.getStatus());
            order.setCustomerId("unlcn");
            order.setCustomerName("中联物流");
            this.insert(order);

            shipmentInfo.setOrderCode(order.getCode());

            //创建订单联系人

            OrderContact orderContact = new OrderContact();
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            // 连接lspm 将司机报班状态调整为已安排--
            headNamePairs.add(new BasicNameValuePair("checkInType", "IU"));
            LOGGER.info("指令新增 连接LSPM 调整司机报班状态:url{},driverId:{},checkinId:{}", getDriverInfoById, shipmentInfoVO.getDriverId(),shipmentInfoVO.getCheckinId());
            String result = HttpClientUtil.get(getDriverInfoById + "/" + shipmentInfoVO.getDriverId()+"/"+shipmentInfoVO.getCheckinId(), headNamePairs, null, socketTimeout);

            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getInteger("code") == 0) {
                orderContact.setContactsName(jsonObject.getJSONObject("data").getString("name"));
                orderContact.setContactsPhone(jsonObject.getJSONObject("data").getString("mobile"));
            }
            orderContact.setOrderCode(order.getCode());
            orderContact.setTenantId(teanantId);
            orderContactService.insert(orderContact);
            order.setOrderContact(orderContact);
            List<LocationVo> locationVoList = new ArrayList<>();
            LocationVo endLocation = endLocation(shipmentInfo, teanantId, authorization);
            if (endLocation == null) {
                LOGGER.error("获取交货点信息失败");
                throw new BaseException("获取交货点信息失败");
            }
            shipmentInfoVO.setEndLocation(endLocation);
            locationVoList.add(endLocation);
            LocationVo startLocation = startLocation(shipmentInfo, teanantId, authorization);
            if (startLocation == null) {
                LOGGER.error("获取发货点信息失败");
                throw new BaseException("获取发货点信息失败");
            }
            shipmentInfoVO.setStartLocation(startLocation);
            locationVoList.add(startLocation);
            order.setLocation(locationVoList);
            //订单地址
            OrderLocation orderLocation = new OrderLocation();
            orderLocation.setOrderId(order.getId());
            orderLocation.setShippingLocationId(endLocation.getId());
            orderLocation.setDeliveryLocationId(startLocation.getId());
            orderLocation.setGmtCreate(new Date());
            orderLocation.setTenantId(teanantId);
            orderLocationService.insert(orderLocation);
            order.setOrderLocation(orderLocation);
            //插入订单ITEM
            List<OrderItem> orderItems = Lists.newArrayList();
            for (OrderVO orderVO : shipmentInfo.getShipTaskDTOList()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(order.getId());
                orderItem.setAmount(1);
                orderItem.setUom("辆");
                orderItem.setIssueItemId(orderVO.getVin());
                orderItem.setMaterial(orderVO.getStanVehicleType());
                orderItem.setTenantId(teanantId);
                orderItem.setGmtCreate(new Date());
                orderItem.setOwnerName(orderVO.getCustomerId());
                orderItem.setItemSourceKey(orderVO.getTaskId());
                orderItemService.insert(orderItem);
                orderItems.add(orderItem);
                order.setDestLocationSequence(orderVO.getDestLocationSequence());
                order.setOriginLocationSequence(orderVO.getOriginLocationSequence());
                insertPriceIncoming(shipmentInfoVO, order, orderVO, orderItem, transTypeId, authorization);
            }
            order.setOrderItemList(orderItems);
            shipmentInfo.setPlateNo(shipmentInfoVO.getPlateNo());
            shipmentInfo.setTransactionCode(shipmentInfoVO.getTransactionCode());
            shipmentOrderDTO.setTransportModeId(String.valueOf(transTypeId));
            shipmentOrderDTO.addOrder(order);
        }
        //下订单，自动生成TMS的运单、任务和装车单
        List<OrderAssign> orderAssignList = autoShipment(authorization, shipmentOrderDTO, addShipmentURL);
        // 回写下发单委托单号（下游系统回写单号）
        if (CollectionUtils.isNotEmpty(orderAssignList)) {
            for (OrderAssign orderAssign : orderAssignList) {
                orderAssign.setGmtAssign(new Date());
                orderAssign.setAssignLog("成功");
                orderAssign.setTenantId(teanantId);
                orderAssignService.insert(orderAssign);
            }
        }
        return true;
    }

    /**
     * 更新订单信息
     */
    private void updateOrder(ShipmentInfoVO shipmentInfoVO, String authorization) {
        ShipmentOrderDTO shipmentOrderDTO = new ShipmentOrderDTO();
        BeanUtils.copyProperties(shipmentInfoVO,shipmentOrderDTO);
        //获取运输方式id
        Long transTypeId = getTransTypeId(shipmentInfoVO.getTransportModeId());
        if (null == transTypeId) {
            LOGGER.error("未查询到对应的运输方式 error:{}", shipmentInfoVO.getTransportModeId());
        }
        shipmentOrderDTO.setTransportModeId(String.valueOf(transTypeId));
        Order updateOrder = new Order();
        List<OrderItem> synTmsList = new ArrayList<>();
        HashMap<String, OrderItem> allOldItem = Maps.newHashMap();
        List<OrderItem> oldItems = orderItemService.orderItemListByCustomerOrderId(shipmentInfoVO.getShipmentId());

        //如果运力 不存在指令生成的订单走新增逻辑
        if (CollectionUtils.isEmpty(oldItems)) {
            shipmentInfoVO.setTransactionCode("IU");
            addOrder(shipmentInfoVO, authorization);
            return;
        } else {
            for (OrderItem oldItem : oldItems) {
                allOldItem.put(oldItem.getItemSourceKey(), oldItem);
            }
        }

        HashMap<String, OrderItem> existsItem = Maps.newHashMap();
        List<OrderLocation> orderLocations = getOrderLocations(oldItems);

        //查询新的和以前的订单明细是否已经存在,便于后续删除更改减掉的车;
        for (OrderVO orderVO : shipmentInfoVO.getShipTaskDTOList()) {
            for (OrderItem oldItem : oldItems) {
                if (oldItem.getItemSourceKey().equals(orderVO.getTaskId())) {
                    existsItem.put(oldItem.getItemSourceKey(), oldItem);
                }
            }
            // 以前orders 肯定存在,不然走新增逻辑
            Wrapper<OrderItem> orderItemWrapper = new EntityWrapper<>();
            orderItemWrapper.eq("item_source_key", orderVO.getTaskId())
                    .eq("is_delete", Integer.valueOf(TableStatusEnum.STATUS_0.getCode()));
            OrderItem orderItems = orderItemService.selectOne(orderItemWrapper);
            //查询订单下面是否有订单明细没有就添加订单有就更新订单明细
            if (Objects.isNull(orderItems)) {
                shipmentInfoVO.setDestLocationProvince(orderVO.getDestLocationProvince());
                shipmentInfoVO.setDestLocationCity(orderVO.getDestLocationCity());
                shipmentInfoVO.setDestLocationCounty(orderVO.getDestLocationCounty());
                shipmentInfoVO.setDestLocationName(orderVO.getDestLocationName());
                shipmentInfoVO.setDestLocationAddress(orderVO.getDestLocationAddress());
                LocationVo endLocation = endLocation(shipmentInfoVO, shipmentInfoVO.getTenantId(), authorization);
                if (endLocation == null) {
                    LOGGER.error("获取交货点信息失败");
                }
                shipmentInfoVO.setEndLocation(endLocation);
                shipmentInfoVO.setOriginLocationProvince(orderVO.getOriginLocationProvince());
                shipmentInfoVO.setOriginLocationCity(orderVO.getOriginLocationCity());
                shipmentInfoVO.setOriginLocationCounty(orderVO.getOriginLocationCounty());
                shipmentInfoVO.setOriginLocationAddress(orderVO.getOriginLocationAddress());
                shipmentInfoVO.setOriginLocationName(orderVO.getOriginLocationName());
                LocationVo startLocation = startLocation(shipmentInfoVO, shipmentInfoVO.getTenantId(), authorization);
                if (startLocation == null) {
                    LOGGER.error("获取发货点信息失败");
                }
                shipmentInfoVO.setStartLocation(startLocation);
                for (int i = 0; i < orderLocations.size(); i++) {
                    OrderLocation location = orderLocations.get(i);
                    if (location.getShippingLocationName()
                            .equals(orderVO.getDestLocationProvince() + orderVO.getDestLocationCity() + orderVO.getDestLocationCounty())
                            && location.getDeliveryLocationName()
                            .equals(orderVO.getOriginLocationProvince() + orderVO.getOriginLocationCity() + orderVO.getOriginLocationCounty())) {
                        OrderItem orderItem = new OrderItem();
                        orderItem.setOrderId(location.getOrderId());
                        orderItem.setAmount(1);
                        orderItem.setUom("辆");
                        orderItem.setIssueItemId(orderVO.getVin());
                        orderItem.setMaterial(orderVO.getStanVehicleType());
                        orderItem.setTenantId(shipmentInfoVO.getTenantId());
                        orderItem.setGmtCreate(new Date());
                        orderItem.setOwnerName(orderVO.getCustomerId());
                        orderItem.setItemSourceKey(orderVO.getTaskId());
                        orderItem.setStartLocation(startLocation);
                        orderItem.setEndLocation(endLocation);
                        orderItemService.insert(orderItem);
                        //需同步tms 数据
                        synTmsList.add(orderItem);
                        //获取原order
                        Order order = selectById(location.getOrderId());
                        insertPriceIncoming(shipmentInfoVO, order, orderVO, orderItem, transTypeId, authorization);
                        break;
                    } else if (i == orderLocations.size() - 1) {
                        //循环到最后没匹配的订单起始地目的地
                        shipmentInfoVO.setTransactionCode("IU");
                        shipmentInfoVO.setIsUpdate(TableStatusEnum.STATUS_1.getCode());
                        //查询order 便于后续查询装车单.
                        Wrapper<Order> orderWrapper = new EntityWrapper<>();
                        orderWrapper.eq("customer_order_id", shipmentInfoVO.getShipmentId())
                                .orderBy("id", false);
                        Order order = selectOne(orderWrapper);
                        EntityWrapper<OrderAssign> orWrapper = new EntityWrapper<>();
                        orWrapper.eq("order_code", order.getCode())
                                .orderBy("id", false);
                        OrderAssign assign = orderAssignService.selectOne(orWrapper);
                        shipmentInfoVO.setShipOrderCode(assign.getConsignCode());
                        ArrayList<OrderVO> list = Lists.newArrayList();
                        list.add(orderVO);
                        shipmentInfoVO.setShipTaskDTOList(list);
                        shipmentInfoVO.setOriginLocationId(orderVO.getOriginLocationId());
                        shipmentInfoVO.setDestLocationId(orderVO.getDestLocationId());
                        //内部已同步TMS 生成运单
                        addOrder(shipmentInfoVO, authorization);
                    }
                }
            }
        }
        // 根据索引移除新指令和以前存在的数据
        if (!existsItem.isEmpty()) {
            existsItem.forEach((key, value) -> {
                allOldItem.remove(key);
            });
        }

        //剩下以前多出的明细(新减少的车)
        if (!allOldItem.isEmpty()) {
            allOldItem.forEach((key, orderItem) -> {
                orderItem.setIsDelete(1);
                orderItemService.updateById(orderItem);
                // 需同步TMS 数据
                synTmsList.add(orderItem);

                Order order = this.selectById(orderItem.getOrderId());
                Wrapper<OrderItem> orderItemWrapper = new EntityWrapper<>();
                orderItemWrapper.eq("order_id", order.getId())
                        .eq("is_delete", 0);
                int count = orderItemService.selectCount(orderItemWrapper);
                if (count == 0) {
                    order.setIsDelete(1);
                    this.updateById(order);
                    deletePriceIncoming(order.getCode(), authorization, shipmentInfoVO);
                } else {
                    deletePriceItem(order.getCode(), authorization, shipmentInfoVO, orderItem);
                }
            });

        }
        updateOrder.setOrderItemList(synTmsList);
        shipmentOrderDTO.addOrder(updateOrder);
        shipmentOrderDTO.setTransactionCode("R");
        //查询order 便于后续查询装车单
        Wrapper<Order> orderWrapper = new EntityWrapper<>();
        orderWrapper.eq("customer_order_id", shipmentInfoVO.getShipmentId())
                .orderBy("id", false);
        Order order = selectOne(orderWrapper);
        EntityWrapper<OrderAssign> orWrapper = new EntityWrapper<>();
        orWrapper.eq("order_code", order.getCode())
                .orderBy("id", false);
        OrderAssign assign = orderAssignService.selectOne(orWrapper);

        shipmentOrderDTO.setShipOrderCode(assign.getConsignCode());
        shipmentOrderDTO.setServiceProviderId(shipmentInfoVO.getServiceProviderId());
        //同个更新tms运单数据
        autoShipment(authorization, shipmentOrderDTO, addShipmentURL);
    }

    /**
     * 获取 已经存在起始地和目的地
     */
    private List<OrderLocation> getOrderLocations(List<OrderItem> oldItems) {
        List<OrderLocation> orderLocations = new ArrayList<>();
        for (OrderItem oldItem : oldItems) {
            if (!Objects.isNull(oldItem)) {
                Wrapper<OrderLocation> orderLocationWrapper = new EntityWrapper<>();
                orderLocationWrapper.eq("order_id", oldItem.getOrderId());
                OrderLocation orderLocation = orderLocationService.selectOne(orderLocationWrapper);
                Wrapper<Location> shippingLocationWrapper = new EntityWrapper<>();
                shippingLocationWrapper.eq("id", orderLocation.getShippingLocationId());
                Location shippingLocation = locationService.selectOne(shippingLocationWrapper);
                orderLocation.setShippingLocationName(shippingLocation.getValue());
                Wrapper<Location> deliveryLocationWrapper = new EntityWrapper<>();
                deliveryLocationWrapper.eq("id", orderLocation.getDeliveryLocationId());
                Location deliveryLocation = locationService.selectOne(deliveryLocationWrapper);
                orderLocation.setDeliveryLocationName(deliveryLocation.getValue());
                orderLocation.setOrderId(oldItem.getOrderId());
                orderLocations.add(orderLocation);
            }
        }
        return orderLocations;
    }

    /**
     * 同步数据删除订单信息
     */
    private Boolean deleteOrder(ShipmentInfoVO shipmentInfoVO, String authorization) {
        ShipmentOrderDTO shipmentOrderDTO = new ShipmentOrderDTO();
        Wrapper<Order> orderWrapper = new EntityWrapper<>();
        orderWrapper.eq("customer_order_id", shipmentInfoVO.getShipmentId())
                .eq("is_delete", "0");
        List<Order> orders = this.selectList(orderWrapper);
        for (Order order : orders) {
            order.setIsDelete(1);
            this.updateById(order);
            Wrapper<OrderAssign> orderAssignWrapper = new EntityWrapper<>();
            orderAssignWrapper.eq("order_code", order.getCode());
            OrderAssign orderAssign = new OrderAssign();
            orderAssign = orderAssignService.selectOne(orderAssignWrapper);
            orderAssign.setIsDelete(1);
            orderAssignService.updateById(orderAssign);

            Wrapper<OrderContact> orderContactWrapper = new EntityWrapper<>();
            orderContactWrapper.eq("order_code", order.getCode());
            OrderContact orderContact = new OrderContact();
            orderContact.setIsDelete(1);
            orderContactService.update(orderContact, orderContactWrapper);

            Wrapper<OrderItem> orderItemWrapper = new EntityWrapper<>();
            orderItemWrapper.eq("order_id", order.getId());
            OrderItem orderItem = new OrderItem();
            orderItem.setIsDelete(1);
            orderItemService.update(orderItem, orderItemWrapper);

            Wrapper<OrderLocation> orderLocationWrapper = new EntityWrapper<>();
            orderLocationWrapper.eq("order_id", order.getId());
            OrderLocation orderLocation = new OrderLocation();
            orderLocation.setIsDelete(1);
            orderLocationService.update(orderLocation, orderLocationWrapper);
            shipmentOrderDTO.setShipOrderCode(orderAssign.getConsignCode());
            shipmentOrderDTO.setTransactionCode("RC");
            LOGGER.info("删除指令调用TMS --->url:{},param:{}", addShipmentURL, JSON.toJSONString(shipmentOrderDTO));
            autoShipment(authorization, shipmentOrderDTO, addShipmentURL);
            deletePriceIncoming(order.getCode(), authorization, shipmentInfoVO);
        }
        // 增加删除调整司机报班状态-->已失效
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        // 连接lspm 将司机报班状态调整为已安排--
        headNamePairs.add(new BasicNameValuePair("checkInType", "RC"));
        LOGGER.info("指令删除 连接LSPM 调整司机报班状态:url{},driverId:{},checkinId:{}", getDriverInfoById, shipmentInfoVO.getDriverId(),shipmentInfoVO.getCheckinId());
        HttpClientUtil.get(getDriverInfoById + "/" + shipmentInfoVO.getDriverId()+"/"+shipmentInfoVO.getCheckinId(), headNamePairs, null, socketTimeout);
        return true;
    }

    /**
     * 根据订单明细从OMS获取应收账款信息
     */
    @Override
    public Map<String, LisaFeeReceivable> queryFeeReceivableOms(List<String> wayBillDtlIds) {
        Map<String, LisaFeeReceivable> map = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(wayBillDtlIds)) {
            List<LisaFeeReceivable> lisaFeeReceivables = baseMapper.queryOrderNoTenant(wayBillDtlIds);
            for (LisaFeeReceivable lisaFeeReceivable : lisaFeeReceivables) {
                map.put(lisaFeeReceivable.getWaybillDtlId(), lisaFeeReceivable);
            }
        }
        return map;
    }

    /**
     * 为TMS提供接口,根据shipOrderCode 查询order及指令号
     */
    @Override
    public Order queryOrderFromTms(Map<String, String> params) {
        if (params != null) {
            EntityWrapper<OrderAssign> ew = new EntityWrapper<>();
            String tmsOrderCode = params.get("tmsOrderCode");
            if (StringUtils.isNotBlank(tmsOrderCode)) {
                ew.eq("consign_code", tmsOrderCode);
                ew.eq("is_delete", TableStatusEnum.STATUS_0.getCode());
                ew.orderBy("id", false);
                List<Order> orders = baseMapper.selectOneNoTenant(ew);
                if (CollectionUtils.isNotEmpty(orders)) {
                    return orders.get(0);
                }
            }
        }
        return null;
    }

    @Override
    public void getErpDispatch(String plateNo, String authorization, String tenantId) {
        ShippingInfoBO shippingInfoBO = erpUtil.getNewestShipByERP(plateNo);
        if (!Objects.isNull(shippingInfoBO)) {
            Wrapper<Order> orderWrapper = new EntityWrapper<>();
            orderWrapper.eq("customer_order_id", shippingInfoBO.getVcshipno());
            List<Order> orderList = baseMapper.selectListNoTenant(orderWrapper);
            // 如果订单不存在就插入，存在则更新
            if (CollectionUtils.isEmpty(orderList)) {
                // 插入
                createOrder(authorization, shippingInfoBO, Long.valueOf(tenantId));
            }
        }
    }

    /**
     * 插入bms收入价格表
     */
    private void insertPriceIncoming(ShipmentInfoVO shipmentInfo,
                                     Order order,
                                     OrderVO orderVO,
                                     OrderItem orderItem,
                                     Long serviceTypeId, String authorization) {
        LOGGER.info("连接BMS 获取收入暂估价--->param:{}", JSON.toJSONString(shipmentInfo));
        if (FourPeopleEnum.JST.getId().equals(shipmentInfo.getServiceProviderId())
                || FourPeopleEnum.JX.getId().equals(shipmentInfo.getServiceProviderId())
                || FourPeopleEnum.LYTD.getId().equals(shipmentInfo.getServiceProviderId())
                || FourPeopleEnum.YJ.getId().equals(shipmentInfo.getServiceProviderId())) {
            PriceIncomingDTO priceIncomingDTO = new PriceIncomingDTO();
            priceIncomingDTO.setTenantId(shipmentInfo.getTenantId());
            priceIncomingDTO.setOrderCode(order.getCode());
            priceIncomingDTO.setCustomerId("unlcn");
            priceIncomingDTO.setCustomerName("中联物流");
            priceIncomingDTO.setItemSourceKey(orderVO.getTaskId());
            priceIncomingDTO.setOrderItemId(orderItem.getId());
            Map<String, BigDecimal> priceAndMiles = priceAndMiles(orderVO.getTaskId(), authorization);
            if (priceAndMiles != null) {
                //暂估价
                priceIncomingDTO.setEstIncomingPrice(priceAndMiles.get("price"));
                //计价里程
                priceIncomingDTO.setMileage(priceAndMiles.get("miles"));
            }
            //车架号
            priceIncomingDTO.setItemUid(orderItem.getIssueItemId());
            LocationVo endLocation = shipmentInfo.getEndLocation();
            LocationVo startLocation = shipmentInfo.getStartLocation();
            priceIncomingDTO.setDepartLocationId(startLocation.getId());
            priceIncomingDTO.setDepartLocationAdCode(startLocation.getAdCode());
            priceIncomingDTO.setTransTypeId(serviceTypeId);
            priceIncomingDTO.setDepartAdressName(startLocation.getValue());
            priceIncomingDTO.setDestLocationId(endLocation.getId());
            priceIncomingDTO.setDestLocationAdCode(endLocation.getAdCode());
            priceIncomingDTO.setDestAdderssName(endLocation.getValue());
            priceIncomingDTO.setCreator(Long.valueOf(shipmentInfo.getCreator()));
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            try {
                LOGGER.info("连接BMS 生成收入单据url:{},param:{}", insertPriceIncomingUrl, JSON.toJSONString(priceIncomingDTO));
                String result = HttpClientUtil.postJson(insertPriceIncomingUrl, headNamePairs, JSON.toJSONString(priceIncomingDTO), socketTimeout);
                if (StringUtils.isBlank(result)) {
                    LOGGER.error("连接BMS生成收入单据失败 未响应---->{}", result);
                }
            } catch (Exception e) {
                LOGGER.error("连接BMS生成收入单据失败 error:{}", e);
            }
        }
    }


    /**
     * 删除bms价格数据
     */
    private void deletePriceIncoming(String orderCode, String authorization, ShipmentInfoVO shipmentInfoVO) {
        LOGGER.info("deletePriceIncoming 删除指令调用BMS 判断四大家--->orderCode:{},shipmentInfoVO:{}", orderCode, JSON.toJSONString(shipmentInfoVO));
        if (FourPeopleEnum.JST.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.JX.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.LYTD.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.YJ.getId().equals(shipmentInfoVO.getServiceProviderId())) {
            PriceIncomingDTO priceIncomingDTO = new PriceIncomingDTO();
            priceIncomingDTO.setOrderCode(orderCode);
            priceIncomingDTO.setCreator(shipmentInfoVO.getTenantId());
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            LOGGER.info("deletePriceIncoming 删除指令调用BMS 删除接口--->url:{},orderCode:{},shipmentInfoVO:{}", deletePriceIncomingUrl, orderCode, JSON.toJSONString(priceIncomingDTO));
            String strReturn = HttpClientUtil.postJson(deletePriceIncomingUrl, headNamePairs,
                    JSON.toJSONString(priceIncomingDTO), socketTimeout);
            LOGGER.info("deletePriceIncoming result {}", strReturn);
        }
    }

    /**
     * 更新bms价格表
     */
    private void deletePriceItem(String orderCode, String authorization, ShipmentInfoVO shipmentInfoVO, OrderItem orderItem) {
        LOGGER.info("deletePriceItem 删除指令调用BMS 判断四大家--->orderCode:{},shipmentInfoVO:{},orderItem:{}", orderCode, JSON.toJSONString(shipmentInfoVO), JSON.toJSONString(orderItem));
        if (FourPeopleEnum.JST.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.JX.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.LYTD.getId().equals(shipmentInfoVO.getServiceProviderId())
                || FourPeopleEnum.YJ.getId().equals(shipmentInfoVO.getServiceProviderId())) {
            PriceIncomingDTO priceIncomingDTO = new PriceIncomingDTO();
            priceIncomingDTO.setOrderCode(orderCode);
            priceIncomingDTO.setOrderItemId(orderItem.getId());
            priceIncomingDTO.setIsDelete(Integer.valueOf(TableStatusEnum.STATUS_1.getCode()));

            priceIncomingDTO.setCreator(shipmentInfoVO.getTenantId());
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            LOGGER.info("deletePriceItem 删除指令调用BMS --->url:{},param:{}", updateIncomingPriceByTaskCodeUrl, JSON.toJSONString(priceIncomingDTO));
            String strReturn = HttpClientUtil.postJson(updateIncomingPriceByTaskCodeUrl, headNamePairs,
                    JSON.toJSONString(priceIncomingDTO), socketTimeout);
            LOGGER.info("deletePriceItem result {}", strReturn);
        }
    }


    private ShipmentInfoVO getGenerateOrder(OrderVO orderVO, List<ShipmentInfoVO> shipmentInfoVOList) {
        for (ShipmentInfoVO shipmentInfoVO : shipmentInfoVOList) {
            if (orderVO.getDestLocationId().equals(shipmentInfoVO.getDestLocationId())
                    && orderVO.getOriginLocationId().equals(shipmentInfoVO.getOriginLocationId())) {
                return shipmentInfoVO;
            }
        }
        ShipmentInfoVO shipmentInfoVO = new ShipmentInfoVO();
        BeanUtils.copyProperties(orderVO, shipmentInfoVO);
        shipmentInfoVOList.add(shipmentInfoVO);
        return shipmentInfoVO;

    }

    /**
     * 获取车.承运商.司机信息
     */
    private CarrierInfoLineVO selectCarrierInfoByPlate(String plate) {
        CarrierInfoLineVO carrierInfoLineVO = null;
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", null));
        List<NameValuePair> params = Lists.newArrayList();
        params.add(new BasicNameValuePair("plate", plate));
        String strReturn = HttpClientUtil.get(getCarrierInfoByPlate, headNamePairs, params, socketTimeout);
        if (StringUtils.isNotBlank(strReturn)) {
            RestfulResponse<CarrierInfoLineVO> restfulResponse = JSON.parseObject(strReturn, new TypeReference<RestfulResponse<CarrierInfoLineVO>>() {
            });
            carrierInfoLineVO = restfulResponse.getData();
        }

        return carrierInfoLineVO;
    }

    /**
     * 获取价格跟里程
     */
    private Map<String, BigDecimal> priceAndMiles(String orderNo, String authorization) {
        Map<String, BigDecimal> result = new HashMap<>();
        Map<String, String> orderno = new HashMap<>();
        orderno.put("orderno", orderNo);
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        String priceAndMiles = HttpClientUtil.postJson(integrationUrl + getPriceAndMilesUrl, headNamePairs,
                JSON.toJSONString(orderno), socketTimeout);
        LOGGER.info("priceAndMiles url:{},param:{}, result {}", integrationUrl + getPriceAndMilesUrl, JSON.toJSONString(orderno), priceAndMiles);
        if (StringUtils.isNotBlank(priceAndMiles)) {
            JSONObject parseObject = JSONObject.parseObject(priceAndMiles);
            if (parseObject.getIntValue("code") == 0) {
                //暂估价
                JSONObject data = parseObject.getJSONObject("data");
                if (data != null) {
                    result.put("price", data.getBigDecimal("price"));
                    //计价里程
                    result.put("miles", data.getBigDecimal("miles"));
                }
            } else {
                LOGGER.error("获取价格里程失败" + parseObject.getString("message"));
//                throw new BaseException("获取价格里程失败" + parseObject.getString("message"));
            }
        } else {
            LOGGER.error("连接OTM获取价格里程失败");
//            throw new BaseException("连接OTM获取价格里程失败");
        }

        return result;
    }

    /**
     * 获取运输方式id
     */
    private Long getTransTypeId(String serviceTypeName) {
        //转换运输方式名称差异
        String typeName = getTrailerTypeName(serviceTypeName);
        List<TransportationTypeDTO> allTransType = mdmUtil.getAllTransType();
        if (CollectionUtils.isNotEmpty(allTransType)) {
            for (TransportationTypeDTO dto : allTransType) {
                if (dto.getValue().equals(typeName)) {
                    return dto.getId();
                }
            }
        }
        return null;
    }

    //转换板车类型名字
    private String getTrailerTypeName(String trailerTypeName) {
        if (StringUtils.isNotBlank(trailerTypeName)) {
            if (trailerTypeName.equals("平板三位板")) {
                return "三位平板";
            }
            if (trailerTypeName.equals("平板四位板")) {
                return "四位平板";
            }
            if (trailerTypeName.equals("六位车")) {
                return "六位平板";
            }
            if (trailerTypeName.equals("单车")) {
                return "单车";
            }
            if (trailerTypeName.equals("中置轴")) {
                return "中置轴";
            }
            if (trailerTypeName.equals("七位车")) {
                return "七位平板";
            }
            if (trailerTypeName.equals("人送地跑")) {
                return "人送地跑";
            }
            if (trailerTypeName.equals("铁路J车")) {
                return "铁运J车";
            }
            if (trailerTypeName.equals("铁运板架箱")) {
                return "铁路板架厢";
            }
            if (trailerTypeName.equals("救援车")) {
                return "救援车";
            }
            if (trailerTypeName.equals("船运")) {
                return "水运";
            }
            if (trailerTypeName.equals("平板五位板")) {
                return "五位平板";
            }

        }
        return trailerTypeName;
    }

    /**
     * 获取交货点地址
     *
     * @param shipmentInfo
     * @param teanantId
     * @param authorization
     * @return
     */
    private LocationVo endLocation(ShipmentInfoVO shipmentInfo, Long teanantId, String authorization) {
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        // 判断订单明细里的交货地点信息是否存在，不存在则插入
        LocationVo endLocation = locationService.getLocationByValue("交货点", shipmentInfo.getDestLocationName());
        if (endLocation == null) {
            Map<String, String> params = new HashMap<>();
            params.put("province", shipmentInfo.getDestLocationProvince());
            params.put("city", shipmentInfo.getDestLocationCity());
            String county = shipmentInfo.getDestLocationCounty();
            if (StringUtils.isNotBlank(county)) {
                params.put("county", county);
            }
            String result = null;
            try {
                LOGGER.info("连接Integration 获取的地编码 url:{} param:{}", integrationUrl + queryListOriginationUrl, JSONObject.toJSONString(params));

                result = HttpClientUtil.postJson(integrationUrl + queryListOriginationUrl, headNamePairs, JSONObject.toJSONString(params), socketTimeout);
            } catch (Exception e) {
                LOGGER.error("连接Integration 获取目的地编码失败 error:{}", e);
                return null;
            }
            if (StringUtils.isBlank(result)) {
                LOGGER.error("连接Integration 获取目的地编码未响应 error");
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (Objects.nonNull(jsonObject)) {
                String data = jsonObject.getString("data");
                if (!StringUtils.isEmpty(data)) {
                    List<OriginationDTO> originationDTOS = JSONObject.parseArray(data, OriginationDTO.class);
                    if (!StringUtils.isEmpty(originationDTOS.get(0).getCountyCode())) {
                        // 调整省市区 组装code
                        endLocation = locationService.insertOrUpdateLocation("交货点",
                                shipmentInfo.getDestLocationProvince() + shipmentInfo.getDestLocationCity() +
                                        (StringUtils.isNotBlank(shipmentInfo.getDestLocationCounty()) ? shipmentInfo.getDestLocationCounty() : ""),
                                shipmentInfo.getDestLocationProvince() + shipmentInfo.getDestLocationCity() +
                                        (StringUtils.isNotBlank(shipmentInfo.getDestLocationCounty()) ? shipmentInfo.getDestLocationCounty() : ""),
                                originationDTOS.get(0).getCountyCode(), teanantId);
                    } else {
                        endLocation = locationService.insertOrUpdateLocation("交货点",
                                shipmentInfo.getDestLocationProvince() + shipmentInfo.getDestLocationCity() +
                                        (StringUtils.isNotBlank(shipmentInfo.getDestLocationCounty()) ? shipmentInfo.getDestLocationCounty() : ""),
                                shipmentInfo.getDestLocationProvince() + shipmentInfo.getDestLocationCity() + shipmentInfo.getDestLocationCity() +
                                        (StringUtils.isNotBlank(shipmentInfo.getDestLocationCounty()) ? shipmentInfo.getDestLocationCounty() : ""),
                                originationDTOS.get(0).getCountyCode(), teanantId);
                    }
                }

            }
        }

        return endLocation;
    }

    /**
     * 获取发货点地址
     *
     * @param shipmentInfo
     * @param teanantId
     * @param authorization
     * @return
     */
    private LocationVo startLocation(ShipmentInfoVO shipmentInfo, Long teanantId, String authorization) {
        // 判断订单明细里的提货地点信息是否存在，不存在则插入
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        LocationVo startLocation = locationService.getLocationByValue("发货点", shipmentInfo.getOriginLocationName());
        if (startLocation == null) {
            Map<String, String> params = new HashMap<>();
            params.put("province", shipmentInfo.getOriginLocationProvince());
            params.put("city", shipmentInfo.getOriginLocationCity());
            String county = shipmentInfo.getOriginLocationCounty();
            if (StringUtils.isNotBlank(county)) {
                params.put("county", county);
            }
            String result = null;
            try {
                LOGGER.info("连接Integration 获取启运地编码 url:{} param:{}", integrationUrl + queryListOriginationUrl, JSONObject.toJSONString(params));
                result = HttpClientUtil.postJson(integrationUrl + queryListOriginationUrl,
                        headNamePairs, JSONObject.toJSONString(params),
                        socketTimeout);
            } catch (Exception e) {
                LOGGER.error("连接Integration 获取启运地编码失败 error:{}", e);
                return null;
            }
            if (StringUtils.isBlank(result)) {
                LOGGER.error("连接Integration 获取启运地编码未响应 error");
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (Objects.nonNull(jsonObject)) {
                String data = jsonObject.getString("data");
                if (!StringUtils.isEmpty(data)) {
                    List<OriginationDTO> originationDTOS = JSONObject.parseArray(data, OriginationDTO.class);
                    if (!StringUtils.isEmpty(originationDTOS.get(0).getCountyCode())) {
                        //调整省市区 组装订单
                        startLocation = locationService.insertOrUpdateLocation("发货点",
                                shipmentInfo.getOriginLocationProvince() + shipmentInfo.getOriginLocationCity() +
                                        (StringUtils.isNotBlank(shipmentInfo.getOriginLocationCounty()) ? shipmentInfo.getOriginLocationCounty() : ""),
                                shipmentInfo.getOriginLocationProvince() + shipmentInfo.getOriginLocationCity() +
                                        (StringUtils.isNotBlank(shipmentInfo.getOriginLocationCounty()) ? shipmentInfo.getOriginLocationCounty() : ""),
                                originationDTOS.get(0).getCountyCode(),
                                teanantId);
                    } else {
                        startLocation = locationService.insertOrUpdateLocation("发货点",
                                shipmentInfo.getOriginLocationProvince() + shipmentInfo.getOriginLocationCity() +
                                        (StringUtils.isNotBlank(shipmentInfo.getOriginLocationCounty()) ? shipmentInfo.getOriginLocationCounty() : ""),
                                shipmentInfo.getOriginLocationProvince() + shipmentInfo.getOriginLocationCity() +
                                        (StringUtils.isNotBlank(shipmentInfo.getOriginLocationCounty()) ? shipmentInfo.getOriginLocationCounty() : ""),
                                originationDTOS.get(0).getCountyCode(),
                                teanantId);
                    }
                }

            }
        }
        return startLocation;
    }

}
